package tools

import (
	"encoding/json"
	"fmt"
)

// DeepCopy 使用 JSON 序列化和反序列化实现深拷贝
func DeepCopy(src interface{}, dst interface{}) error {
	// 将源对象序列化为JSON字节
	data, err := json.Marshal(src)
	if err != nil {
		return err
	}

	// 将JSON字节反序列化到目标对象
	err = json.Unmarshal(data, dst)
	if err != nil {
		return err
	}

	return nil
}

func RunMain() {
	type Address struct {
		Street string
		City   string
	}
	type Person struct {
		Name    string
		Age     int
		Address Address
	}

	original := Person{
		Name: "Alice",
		Age:  30,
		Address: Address{
			Street: "123 Main St",
			City:   "Wonderland",
		},
	}

	var copied Person

	err := DeepCopy(original, &copied)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Original:", original)
	fmt.Println("Copied:", copied)

	// 修改副本，确保它不会影响原始对象
	copied.Name = "Bob"
	copied.Address.City = "Dreamland"

	fmt.Println("After modification")
	fmt.Println("Original:", original)
	fmt.Println("Copied:", copied)
}
